package com.sparrow.common.console.domain;

import org.springframework.core.convert.ConversionService;

import java.lang.reflect.Method;

public class ConsoleCommandWrapper {
    private final Object target;
    private final Method method;
    private final ConversionService conversionService;

    public ConsoleCommandWrapper(Object target, Method method, ConversionService conversionService) {
        this.target = target;
        this.method = method;
        this.conversionService = conversionService;
    }

    public Object execute(Object[] arguments) {
        final Class<?>[] types = method.getParameterTypes();
        if (arguments.length != types.length) {
            throw new RuntimeException("指令参数长度不正确");
        }

        Object[] args = new Object[arguments.length];
        try {
            for (int i = 0; i < arguments.length; i++) {
                args[i] = conversionService.convert(arguments[i], types[i]);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("参数转换时出现异常", e);
        }

        try {
            return method.invoke(target, args);
        } catch (Exception e) {
            throw new RuntimeException("方法执行时出现异常", e);
        }
    }

}
